import models
import types
import logging
import sys

def get_text(path):
    paste = models.Paste.fetch(path)
    if not paste:
        return None
    return paste.code

def import_module(path):
    path = str(path)
    module_path = path.replace('/', '.').strip('.')
    if module_path in sys.modules: 
        return sys.modules[module_path]
    
    module = get_module(path, True)
    if '.' in module_path:
        parent_path = '.'.join(module_path.split('.')[:-1])
        
        
        parent = import_module('/' + parent_path.replace('.', '/'))
        if not parent:
            raise Exception("could not import parent module of '{}'".format(parent_path))
        parent.__dict__[module_path.split('.')[-1]] = module
        
    return sys.modules.setdefault(module_path, module)
    

def get_module(path, for_import=False):
    module_name = path.replace('/', '.').strip('.')
    if for_import and path == '/zoil':
        # return 'base' module
        return types.ModuleType(str(module_name))
    
    paste = models.Paste.fetch(path[5:] if for_import else path)
    if not paste:
        return None
    if not 'python' in paste.mimetype:
        # return empty module
        return types.ModuleType(str(module_name))
    
    code = paste.code
    for line in code.splitlines():
        if line.startswith('import ') or line.startswith('from '):
            module_path = line.split(' ')[1]
            if not module_path.startswith('zoil.'): continue
            module_path = module_path.replace('.', '/')
            if not module_path.startswith('/'):
                module_path = '/' + module_path
            if module_path != path:
                import_module(module_path)
    
    module = types.ModuleType(str(module_name))
    exec code in module.__dict__
    return module  